package com.heima.datasync.service.impl;

import com.heima.datasync.mapper.ApArticleMapper;
import com.heima.datasync.service.EsDataService;
import com.heima.datasync.vo.SearchArticleVO;
import com.heima.es.service.EsService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
@Slf4j
public class EsDataServiceImpl implements EsDataService {

    @Autowired
    ApArticleMapper apArticleMapper;

    @Autowired
    EsService<SearchArticleVO> esService;

    /**
     * 数据库查询导入到索引库（全量导入）
     * @return
     */
    @Override
    public ResponseResult dataInit() {
        //1 查询数据库文章列表
        List<ApArticle> articleList = apArticleMapper.findAllArticles();
        if (articleList == null || articleList.size() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "数据库文章信息不存在");
        }

        //2 封装到 SearchArticleVo 对象中
        List<SearchArticleVO> articleVOList = articleList.stream()
                .map(apArticle -> {
                    SearchArticleVO searchArticleVO = new SearchArticleVO();
                    BeanUtils.copyProperties(apArticle, searchArticleVO);
                    searchArticleVO.setLayout(apArticle.getLayout().intValue());
                    return searchArticleVO;
                }).collect(Collectors.toList());

        //3 执行批量导入索引库
        esService.saveBatch(articleVOList, "app_info_article");
        return null;
    }
}